// index.js
// 获取应用实例
import led from '../../api/led';

const speeds = [];
for (let i = 0; i <= 1000; i += 50) {
  speeds.push(i)
}

const app = getApp()
Page({
  data: {
    deviceId: '',
    speeds,
    speed: 500,
    value: [10],
    isOn: false,
    isStream: false,
    online: false
  },

  onLoad(options) {
    // console.log(options.online)
    this.setData({
      deviceId: options.deviceId,
      isOn: false,
      isStream: false,
      online: options.online
    })
    this.isOnline(this.data.online)
    // console.log('Device:' + this.data.deviceId);
  },
  controlLedOnOrOff() {
    if (!this.isOnline(this.data.online)) {
      return;
    }
    this.setData({
      isOn: !this.data.isOn,
      isStream: false
    })
    led.controlLed(this.data.isOn, this.data.deviceId);
  },
  controlStreamOnOff() {
    if (!this.isOnline(this.data.online)) {
      return;
    }
    this.setData({
      isOn: false,
      isStream: !this.data.isStream,
    })
    led.controlStreamOnOff(this.data.isStream, this.data.speed, this.data.deviceId)
  },
  controlStreamLed(e) {
    if (!this.isOnline(this.data.online)) {
      return;
    }
    const index = e.detail.value[0];
    this.setData({
      isOn: false,
      speed: this.data.speeds[index],
      isStream: true
    })
    led.controlStreamLedSpeed(this.data.speed, this.data.deviceId);
  },
  isOnline(online) {
    console.log(online);
    if (online === 'false') {
      wx.showToast({
        title: "设备离线",
        icon: 'error',
        duration: 1500,
        mask: true,
      })
      return 0;
    }
    return 1;
  }
})